package com.lbloca.locate.ui.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.gyf.immersionbar.ImmersionBar;
import com.lbloca.locate.R;
import com.lbloca.locate.beans.ResponseBean;
import com.lbloca.locate.biz.AppBiz;
import com.lbloca.locate.ui.base.BaseActivity;
import com.lbloca.locate.utils.GsonUtil;
import com.lbloca.locate.utils.LogUtils;
import com.lbloca.locate.utils.PermissionUtils;
import com.lbloca.locate.utils.ToastUtils;
import com.lbloca.locate.weight.CustomTextView;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

public class AddAttentionPeopleActivity extends BaseActivity {
    private static final String TAG = "AddAttentionPeopleActivity";

    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_et_phone)
    EditText mEtPhone;
    @BindView(R.id.id_rl_add_wechat)
    RelativeLayout mRlAddWechat;
    @BindView(R.id.id_ct_add_location)
    CustomTextView mCtAddLocation;
    @BindView(R.id.id_tv_address_book)
    TextView mTvAddressBook;


    protected final int REQUEST_ADDRESSBOOK = 11;

    @Override
    protected void initEvents() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_attention_people;
    }

    @Override
    protected void initView() {

    }


    @OnClick({R.id.id_tv_address_book, R.id.id_ct_add_location,R.id.id_rl_back})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.id_tv_address_book:
                PermissionUtils.requestPermission(this, new String[]{Manifest.permission.READ_CONTACTS}, new PermissionUtils.Callback() {
                    @Override
                    public void onGranted(String permission) {
//                        ToastUtils.showShort("onGranted");
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.PICK");
                        intent.addCategory("android.intent.category.DEFAULT");
                        intent.setType("vnd.android.cursor.dir/phone_v2");
                        startActivityForResult(intent, REQUEST_ADDRESSBOOK);
                    }

                    @Override
                    public void onDenied(String permission) {
                        ToastUtils.showShort("onDenied");
                    }
                });
                break;
            case R.id.id_ct_add_location:
                String phone = mEtPhone.getText().toString();
                if (!TextUtils.isEmpty(phone) && isPhoneNumber(phone)) {
                    AppBiz.getInstance().addFriend(phone, new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            e.printStackTrace();
                            ToastUtils.showShort("添加失败");
                        }
                        @Override
                        public void onResponse(String response, int id) {
                            LogUtils.i(TAG,response);
                            if (!TextUtils.isEmpty(response)) {
                                ResponseBean bean = GsonUtil.json2Bean(response, ResponseBean.class);
                                if (bean.getCode() >= 0){
                                    ToastUtils.showShort("添加成功");
                                    mEtPhone.setText("");
                                    AddAttentionPeopleActivity.this.finish();
                                }else{
                                    ToastUtils.showShort("添加失败");
                                }
                            }
                        }
                    });
                } else {
                    ToastUtils.showShort("请输入正确的手机号码");
                }
                break;
            case R.id.id_rl_back:
                AddAttentionPeopleActivity.this.finish();
                break;
            default:
                break;
        }
    }


    public static void start(Context context) {
        Intent intent = new Intent(context, AddAttentionPeopleActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .navigationBarDarkIcon(true)
                .titleBar(mToolbar)
                .init();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ADDRESSBOOK) {
            try {
                if (data != null) {
                    Uri uri = data.getData();
                    String phoneNum = null;
                    String contactName = null;
                    // 创建内容解析者
                    ContentResolver contentResolver = getContentResolver();
                    Cursor cursor = null;
                    if (uri != null) {
                        cursor = contentResolver.query(uri, new String[]{"display_name", "data1"}, null, null, null);
                    }
                    while (cursor.moveToNext()) {
                        contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        phoneNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    }
                    cursor.close();
                    if (phoneNum != null) {
                        phoneNum = phoneNum.replaceAll("-", " ");
                        phoneNum = phoneNum.replaceAll(" ", "");
                    }
//                    Toast.makeText(this, contactName + "==" + phoneNum, Toast.LENGTH_LONG).show();

                    mEtPhone.setText(phoneNum);
                    mEtPhone.setSelection(phoneNum.length());

                } else {
                    Toast.makeText(this, "用户未选择联系人", Toast.LENGTH_LONG).show(); //用户未选择联系人
                }
            } catch (Exception e) {
                Toast.makeText(this, "获取联系人失败", Toast.LENGTH_LONG).show();
            } //异常
        }
    }

    public static boolean isPhoneNumber(String input) {// 判断手机号码是否规则
        String regex = "(1[0-9][0-9]|15[0-9]|18[0-9])\\d{8}";
        Pattern p = Pattern.compile(regex);
        return p.matches(regex, input);//如果不是号码，则返回false，是号码则返回true
    }
}
